#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

#include "debug.h"
#include "os_api.h"
#include "dev_api.h"

#define _STACK_SIZE		(1024*3)
static void* _task_stack = NULL;

static OSTaskRef _task_ref = NULL;

static OSATimerRef _task_delete_timer_ref = NULL;

void DeleteTaskByTimer(UINT32 id)
{
    OSA_STATUS status;

    if(_task_ref)
    {
        status = OSATaskDelete(_task_ref);
        ASSERT(status == OS_SUCCESS);
        _task_ref = NULL;
	   
        if(_task_stack)
        {
            free(_task_stack);
            _task_stack = NULL;
        }
    }

    OSATimerDelete (_task_delete_timer_ref);
}

void wait_sim_ready(void)
{
    int count = 10;
    while(count-- && dev_GetSIMReady() == FALSE){	
        LOG_PRINTF("dev_GetSIMReady not ready!");
        OSATaskSleep(200);
    }
}

static void _task(void *ptr)
{
    int count = 2;
	BOOL ret = FALSE;
	char imsi_str[32] = {0};
	char iccid_str[32] = {0};	    
    
    wait_sim_ready();

    memset(imsi_str, 0x00, sizeof(imsi_str));
    ret = dev_GetSIMImsi(imsi_str, sizeof(imsi_str));
    LOG_PRINTF("dev_GetSIMImsi ret %d, imsi: %s\n", ret, imsi_str);

    memset(iccid_str, 0x00, sizeof(iccid_str));
    ret = dev_GetSIMIccid(iccid_str, sizeof(iccid_str));
    LOG_PRINTF("dev_GetSIMIccid ret %d, iccid: %s\n", ret, iccid_str);
	
    while(count--){
    
        if (CM_SIM_0 != dev_GetSIMId()){
            dev_SetSIMId(CM_SIM_0);
        } else if (CM_SIM_1 != dev_GetSIMId()){
            dev_SetSIMId(CM_SIM_1);
        }

        OSATaskSleep(3*200);

        wait_sim_ready();

        memset(imsi_str, 0x00, sizeof(imsi_str));
        ret = dev_GetSIMImsi(imsi_str, sizeof(imsi_str));
        LOG_PRINTF("SIM_%d,dev_GetSIMImsi ret %d, imsi: %s\n", dev_GetSIMId(), ret, imsi_str);

        memset(iccid_str, 0x00, sizeof(iccid_str));
        ret = dev_GetSIMIccid(iccid_str, sizeof(iccid_str));
        LOG_PRINTF("SIM_%d,dev_GetSIMIccid ret %d, iccid: %s\n", dev_GetSIMId(), ret, iccid_str);

        OSATaskSleep(15*200);
    }

    count = 180;
    dev_EnableSIMDetect(1, 1); // 启动SIM卡热插拔，仅CM_SIM_0（卡1）支持热插拔
    // 此阶段可以插拔SIM卡测试，SIM卡热插拔，dev_EnableSIMDetect 也可放在代码初始化开始时
    while(count--){
        LOG_PRINTF("dev_GetSIMReady: %d\n", dev_GetSIMReady());
        OSATaskSleep(200);
    }

	OSATimerCreate(&_task_delete_timer_ref);
	OSATimerStart(_task_delete_timer_ref, 400, 0, DeleteTaskByTimer, 0);
}


int main(void)
{	
    int ret;

	_task_stack = malloc(_STACK_SIZE);
    ASSERT(_task_stack != NULL);
	
    ret = OSATaskCreate(&_task_ref, _task_stack, _STACK_SIZE, 100, "_task", _task, NULL);
    ASSERT(ret == OS_SUCCESS);
	
	return 0;
}